package com.weiadmin.controller.system;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.weiadmin.common.BaseController;
import com.weiadmin.dao.SettingDao;
import com.weiadmin.model.system.SettingOptionModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * 系统设置
 * @author: shizhongyu
 * @date: 2023年05月30日 17:45
 */
@RestController
@RequestMapping("/admin/setting")
public class SettingController extends BaseController {
    @Autowired
    SettingDao settingMapper;
    @GetMapping("/index")
    public ModelAndView index(Model model) {
        ModelAndView modelAndView = display("setting/index");
        SettingOptionModel settingOption = settingMapper.selectOne(new QueryWrapper<SettingOptionModel>().lambda().eq(SettingOptionModel::getOptionName, "info"));
        System.out.println(settingOption.getOptionValue());

        JSONObject map = JSONUtil.parseObj(settingOption.getOptionValue());
        //赋值操作
        model.addAttribute("info",map);
        return modelAndView;
    }

    @PostMapping("/update")
    public ResponseEntity<?>  update(@RequestBody Map params){
        SettingOptionModel settingOption = settingMapper.selectOne(new QueryWrapper<SettingOptionModel>().lambda().eq(SettingOptionModel::getOptionName, "info"));
        if(settingOption==null){
            SettingOptionModel option = new SettingOptionModel();
            option.setOptionName("info");
            String value = JSONUtil.toJsonStr(params);
            option.setOptionValue(value);
            settingMapper.insert(option);
        }else{
            String value = JSONUtil.toJsonStr(params);
            settingOption.setOptionValue(value);
            settingMapper.updateById(settingOption);
        }
        return success("保存成功！",params);
    }

}
